<template>
  <div class=" flex flex-col h-full">
    <!-- 主要内容区 -->
    <div class="flex-1 flex flex-col overflow-hidden">
      <!--来电面板-->
      <template v-if="callState.isRing">
        <div
            class="relative flex-1 flex flex-col items-center justify-center bg-gradient-to-br from-gray-900 to-gray-800 p-6">
          <!-- 来电者信息 -->
          <div class="flex flex-col items-center mb-8">
            <div class="relative mb-6">
              <img :src="contact.avatarUrl?contact.avatarUrl:'https://picsum.photos/id/1027/40/40'" alt="Emily's avatar"
                   class="w-24 h-24 rounded-full border-4 border-blue-500 shadow-xl"/>
              <!-- 视频/语音标识 -->
              <div
                  class="absolute -bottom-3 -right-3 w-12 h-12 bg-blue-500 rounded-full flex items-center justify-center shadow-lg">
                <i :class="isVideoCall ? 'fa fa-video-camera text-xl' : 'fa fa-phone text-xl'" class="text-white"></i>
              </div>
            </div>
            <h2 class="text-2xl font-bold text-white mb-2">
              {{ contact.aliasName ? contact.aliasName : contact.nickname }}</h2>
            <p class="text-gray-300 text-sm">{{ tipMsg }}</p>
          </div>

          <!-- 铃声动画 -->
          <div class="absolute inset-0 flex items-center justify-center pointer-events-none">
            <div class="w-64 h-64 rounded-full border-4 border-blue-500/30 animate-ping"></div>
            <div class="w-72 h-72 rounded-full border-4 border-blue-500/20 animate-ping"
                 style="animation-delay: 0.5s"></div>
            <div class="w-80 h-80 rounded-full border-4 border-blue-500/10 animate-ping"
                 style="animation-delay: 1s"></div>
          </div>

          <!-- 操作按钮 -->
          <div class="flex items-center space-x-8 mt-auto mb-12">
            <!--拒接-->
            <button @click="rejectCall"
                    class="w-16 h-16 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center text-white transition-colors shadow-lg transform hover:scale-105 transition-transform">
              <i class="fa fa-phone fa-rotate-135 text-2xl"></i>
            </button>
            <!--接听-->
            <button @click="answerCall"
                    class="w-16 h-16 bg-green-500 hover:bg-green-600 rounded-full flex items-center justify-center text-white transition-colors shadow-lg transform hover:scale-105 transition-transform">
              <i class="fa fa-phone text-2xl"></i>
            </button>
          </div>
        </div>
      </template>
      <!--通话面板 v-show="callState.status!==CallStatus.Noting" -->
      <template >
        <div class="relative flex-1 flex flex-col bg-gradient-to-br from-gray-900 to-gray-800">

          <!-- 视频/语音内容区域 -->
          <div class="flex-1 flex items-center justify-center p-4">
            <!-- 视频卡片容器 -->
            <div
                class="relative w-full max-w-4xl aspect-video bg-gray-800 rounded-2xl overflow-hidden shadow-2xl border-4 border-white/10">
              <!--              <img src="https://picsum.photos/id/1027/800/600" alt="Video call with Emily"
                                 class="w-full h-full object-cover" />-->
              <video ref="remoteVideoRef" class="w-full h-full object-cover"></video>

              <!-- 视频底部信息 -->
              <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-4">
                <div class="flex justify-between items-center">
                  <div class="flex items-center">
                    <img :src="contact.avatarUrl?contact.avatarUrl:'https://picsum.photos/id/1027/40/40'"
                         alt="Emily's avatar" class="w-10 h-10 rounded-full border-2 border-white mr-3"/>
                    <div>
                      <h2 class="text-lg font-medium text-white">
                        {{ contact.aliasName ? contact.aliasName : contact.nickname }}</h2>
                      <div class="flex items-center">
                        <span class="w-2 h-2 bg-green-500 rounded-full mr-1"></span>
                        <span class="text-xs text-gray-300">正在说话</span>
                      </div>
                    </div>
                  </div>
                  <span v-show="callState.status===CallStatus.Talking"
                        class="text-sm text-gray-300">{{ formatTime }}</span>
                </div>
              </div>

              <!-- 视频顶部控制 -->
              <div class="absolute top-4 right-4 flex space-x-2">
                <button
                    class="w-9 h-9 bg-black/50 backdrop-blur-sm hover:bg-black/70 rounded-full flex items-center justify-center text-white transition-colors">
                  <i class="fa fa-expand"></i>
                </button>
              </div>
            </div>
            <!-- 语音通话背景 -->
            <!--            <div v-if="callType===0" class="flex flex-col items-center justify-center">
                          <audio ref="remoteVideoRef" class="w-full h-full object-cover"></audio>

                          <div
                              class="w-40 h-40 bg-blue-500/20 backdrop-blur-sm rounded-full flex items-center justify-center mb-6 border border-blue-500/30 animate-pulse">
                            <i class="fa fa-phone text-5xl text-blue-400"></i>
                          </div>
                          <h2 class="text-2xl font-medium text-white mb-2">{{ tipMsg }}</h2>
                          <p v-show="callState.status===CallStatus.Talking" class="text-gray-400">{{ formatTime }}</p>
                        </div>-->
          </div>

          <!-- 悬浮在视频底部的通话控制区 -->
          <div class="absolute bottom-4 left-0 right-0 flex justify-center px-4">
            <div
                class="bg-black/40 backdrop-blur-md rounded-full p-3 flex items-center space-x-3 shadow-lg">
              <button @click="()=>{isVideoCall = !isVideoCall}"
                      class="w-12 h-12 bg-white/10 hover:bg-white/20 rounded-full flex items-center justify-center text-white transition-colors">
                <i :class="isVideoCall ? 'fa fa-video-slash' : 'fa fa-video-camera'"></i>
              </button>

              <!-- 结束通话按钮 -->
              <button @click="endCall"
                      class="w-14 h-14 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center text-white transition-colors shadow-lg transform hover:scale-105 transition-transform">
                <i class="fa fa-phone fa-rotate-135"></i>
              </button>

              <button
                  class="w-12 h-12 bg-white/10 hover:bg-white/20 rounded-full flex items-center justify-center text-white transition-colors">
                <i class="fa fa-volume-up"></i>
              </button>
            </div>

            <!--            <div v-if="callType===0"
                             class="bg-black/40 backdrop-blur-md rounded-full p-3 flex items-center space-x-3 shadow-lg">
                          &lt;!&ndash; 结束通话按钮 &ndash;&gt;
                          <button @click="endCall"
                                  class="w-14 h-14 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center text-white transition-colors shadow-lg transform hover:scale-105 transition-transform">
                            <i class="fa fa-phone fa-rotate-135"></i>
                          </button>
                        </div>-->
          </div>

          <!-- 视频通话时显示的自己的小窗口 -->
          <div v-show="isVideoCall"
               class="absolute top-4 right-4 w-36 h-48 rounded-xl overflow-hidden border-2 border-white shadow-lg transform hover:scale-105 transition-transform">
            <!--
                        <img src="https://picsum.photos/id/1005/144/192" alt="Your video" class="w-full h-full object-cover">
            -->
            <video ref="localVideoRef" class="w-full h-full object-cover"></video>

            <div class="absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-transparent"></div>
            <div class="absolute bottom-2 left-2">
              <p class="text-xs font-medium text-white">你</p>
            </div>
          </div>

          <!-- 通话状态指示 -->
          <div class="absolute top-4 left-4 bg-black/50 backdrop-blur-sm rounded-full px-3 py-1.5 flex items-center">
            <span class="w-2 h-2 bg-red-500 rounded-full mr-2 animate-pulse"></span>
            <span class="text-xs text-white">{{ statusMsg }}</span>
          </div>
        </div>
      </template>

    </div>
  </div>
</template>

<script setup>
import {computed, defineEmits, defineExpose, defineProps, inject, nextTick, onMounted, ref, toRaw} from 'vue';
import 'element-plus/es/components/message/style/css';
import {ElMessage} from 'element-plus'
import {CallStatus, Signal} from "@/models/call.ts";
import {closeCamera, getLocalStream, hasAudioTrack} from "@/utils/my_media_device.js"
import {useLoginStore} from "@/stores/login_store.ts";
import {getCalleeRef} from "@/models/call_service.ts";

//父组件传值时的定义
const props = defineProps({
  callType: Number, // 语音/视频通话 0-语音通话、1-视频通话
  callState: Object, //状态数据
  contact: Object, //联系人信息
});

console.log("[VideoCallPane] callType = " + props.callType)

const isVideoCall = ref(true);
// watch(() => props.callType, (newVal, oldVal) => {
//   isVideoCall.value = (newVal === 1);
// })

const emits = defineEmits([
  "updateCallType",
  "updateCallState"
])

//本地流
// let local_stream = ref(null); // local video stream
// 本地视频
const localVideoRef = ref();
// 远程视频
const remoteVideoRef = ref();

const loginStore = useLoginStore();
const userId = loginStore.userInfo.uid;
const signalWS = inject('signalWS');

let caller = ref(null);
let callee = getCalleeRef();

const timeoutTimer = ref(30); // 30s还未打通则取消
const timer = ref(0); //通话时长计时器：非精确值
let timerInterval = null;
let timeoutInterval = null;
//超时未打通的计时器
const startTimeoutTimer = () => {
  timeoutInterval = setInterval(() => {
    timeoutTimer.value--;

    if (timeoutTimer.value <= 0) {
      clearInterval(timeoutInterval);

      if (props.callState.status === CallStatus.Call) {
        console.log("拨打超时了，即将取消call..");
        endCall(); //拨打超时则取消call
      }
    }
  }, 1000);
};
// 通话时长计时-开始
const startTimer = () => {
  timerInterval = setInterval(() => {
    timer.value++;
  }, 1000);
}
// 通话时长计时-停止
const stopTimer = () => {
  if (timerInterval) {
    clearInterval(timerInterval);
    timer.value = 0;
    timerInterval = null;
  }
}

// 接听电话
const answerCall = () => {
  emits('updateCallState',CallStatus.Talking,false);

  getLocalStream().then(localStream => {
    console.debug(`>>> 本地流 stream.id=${localStream.id}. 是否含有音轨? ${hasAudioTrack(localStream)} `)
    if (localVideoRef.value) { //当仅语音通话时，应该是没有localVideoRef值的
      //添加本地媒体流（不能放自己的声音）
      localVideoRef.value.srcObject = localStream;
      localVideoRef.value.muted = true;
      localVideoRef.value.play(); //播放
    }
    callee.value?.accept(localStream);
  });
};

// 拒接电话
const rejectCall = () => {
  callee.value?.reject();

  emits('updateCallState',CallStatus.Noting,false);
};

// 结束通话,挂断
const endCall = () => {
  console.log("click endCall...")
  //如果在拨电话：取消拨打
  if (props.callState.status === CallStatus.Call) {
    caller.value?.cancel();
  }
  //如果正在打电话：挂断电话
  else if (props.callState.status === CallStatus.Talking) {
    caller.value?.hangup();
    callee.value?.hangup();
  }
  //重置状态
  emits('updateCallState',CallStatus.Noting,false);

  stopTimer(); //停止计时

  closeCamera(localVideoRef.value);
  closeCamera(remoteVideoRef.value);
};

/**
 * 主动发起呼叫
 * 我呼叫对方
 */
const callOut = (calleeId, isGroup) => {
  if (props.callState.status !== CallStatus.Noting) {
    return;
  }
  if (isGroup) {
    ElMessage.info("暂时不支持群组通话");
    return;
  }
  if (!calleeId || userId === calleeId) {
    console.warn("calleeId值不对，请检查! 不能为空，不能等于当前userId")
    return;
  }
  console.log("调用 callOut ...");

  emits('updateCallState',CallStatus.Call);

  startTimeoutTimer(); //超时不接听则取消call

  //添加本地媒体流（不能放自己的声音）
  getLocalStream(false).then(localStream => {
    console.debug(`>>> 本地流 stream.id=${localStream.id}. 是否含有音轨? ${hasAudioTrack(localStream)} `)

    caller.value = signalWS.createCaller(userId, calleeId, isGroup);
    caller.value.localStream = localStream;
    //创建和对方的连接
    caller.value.call(props.callType, signalHandle); //在这里赋值的DateConn

    if (localVideoRef.value) { //当仅语音通话时，应该是没有localVideoRef值的
      //添加本地媒体流（不能放自己的声音）
      localVideoRef.value.srcObject = localStream;
      localVideoRef.value.muted = true;
      localVideoRef.value.play(); //播放
    }
  });
}

//回应信号处理逻辑
const signalHandle = (command, extend) => {
  if (command === Signal.SetCallType && extend) {
    emits('updateCallType',Number(extend));
    return;
  }

  //如果对方同意，再call对方
  if (command === Signal.ACCEPT) {
    console.log("对方已接听...");
    emits('updateCallState',CallStatus.Talking, false);

    caller.value.doTalk(remoteVideoRef.value); //真正调用call接口去通话

    startTimer(); //开始计时
    return;
  }

  emits('updateCallState',CallStatus.Noting, false);

  switch (command) {
    case Signal.HANGUP: //挂断
      console.log("对方已挂断...");
      ElMessage.info("对方已挂断");
      break;
    case Signal.REJECT: //拒接
      console.log("对方已拒绝...");
      ElMessage.info("对方已拒绝");
      break;
    case Signal.CANCEL: //取消
      console.log("对方已取消...");
      ElMessage.info("对方已取消");
      break;
    default:
      console.warn("对方发送未知命令:", command);
  }
  //关闭调双方
  callee.value?.close();
  caller.value?.close();

  stopTimer(); //停止计时

  // 关掉摄像头
  closeCamera(localVideoRef.value);
  closeCamera(remoteVideoRef.value);
};

// 文本描述
const tipMsg = computed(() => {
  // props.callState.isCalling
  console.log("props.callState = ", toRaw(props.callState));

  if (props.callState.isRing) {
    return "hahaha";
  }

  if (props.callState.status === CallStatus.Call) {
    return "正在呼叫中";
  } else if (props.callState.status === CallStatus.Talking) {
    return "正在通话中";
  } else {
    return "通话已结束";
  }
});

const statusMsg = computed(() => {
  if (props.callState.status === CallStatus.Talking) {
    return "通话中";
  } else {
    return "等待通话";
  }
});

const formatTime = computed(() => {
  const t = timer.value;
  const h = Math.floor(t / 3600);
  const m = Math.floor((t % 3600) / 60);
  const s = t % 60;
  return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
});

// onUnmounted(endCall);
onMounted(async () => {
  await nextTick();
  // console.debug("callType= "+ props.callType.value+"\t remoteVideoRef = "+remoteVideoRef.value);
  // signalWS?.bindCallVideo(remoteVideoRef.value, startTimer); //绑定video元素

  signalWS?.bindCallMeCallback((mediaConn) => {
    console.log("[peer] call ... ")
    if (remoteVideoRef.value) {
      callee.value.answerTalk(remoteVideoRef.value, mediaConn); //和对方开始通话

      startTimer(); //开始计时
    } else {
      throw new Error("remoteVideo 元素不能为null");
    }
  });
});

//暴露需要被父组件访问的方法或属性
defineExpose({
  signalHandle,
  callOut,
  endCall,
});
</script>

<style scoped>
/* 自定义动画 */
@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

@keyframes ping {
  0% {
    transform: scale(0.8);
    opacity: 1;
  }
  75%, 100% {
    transform: scale(1.5);
    opacity: 0;
  }
}

.animate-pulse {
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

.animate-ping {
  animation: ping 2s cubic-bezier(0, 0, 0.2, 1) infinite;
}

/* 渐变背景 */
.bg-gradient {
  background: linear-gradient(135deg, #4a5568 0%, #1a202c 100%);
}
</style>
